package com.weibo.api;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.weibo.WBException;
import com.weibo.util.HttpKit;

/**
 * 消息推送格式切换接口-默认json可切换兼容微信的xml
 * @author L.cm
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @date 2014-4-17 上午10:48:02
 */
public class WBMsgFormat {

	// 设置消息切换的url
	private static final String _SET_FORMAT_URL = "https://api.weibo.com/2/eps/push/set_format.json";
	
	public static final String _XML  = "XML";
	public static final String _JSON = "JSON";
	
	public WBMsgFormat() {}

	public static WBMsgFormat me() {
		return new WBMsgFormat();
	}
	
	/**
	 * 消息推送格式切换
	 * @param format
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws WBException 
	 */
	public JSONObject setFormat(String format) throws UnsupportedEncodingException, WBException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", WeiBo.props.get("access_token"));
		params.put("format", format);
		String reslut = HttpKit.post(_SET_FORMAT_URL, params);
		if (StringUtils.isBlank(reslut)) {
			return null;
		}
		JSONObject json = JSONObject.parseObject(reslut);
		if (json.containsKey("error_code")) {
			throw new WBException(json.toJSONString());
		} else {
			return json;
		}
	}
	
	/*
	// 成功返回
	{
		"uid": "123456789",
		"format": XML
	}

	// 失败返回
	{
		"request": "2/eps/push/set_format.json",
		"error_code": 284XX,
		"error": "error message."
	}
	*/
	public static void main(String[] args) {
		try {
			System.out.println(WBMsgFormat.me().setFormat(WBMsgFormat._JSON));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (WBException e) {
			e.printStackTrace();
		}
	}
}
